package com.oamic.sdk.picker.pickerview.view;

import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.oamic.sdk.picker.R;
import com.oamic.sdk.picker.pickerview.configure.PickerOptions;
import com.oamic.sdk.picker.pickerview.listener.ISelectTimeCallback;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * 时间选择器
 * Created by Sai on 15/11/22.
 * Updated by XiaoSong on 2017-2-22.
 */
public class TimePickerView extends BasePickerView implements View.OnClickListener {
    
    //自定义控件
    private WheelTimeWithWeek mWheelTimeWithWeek;
    private static final String TAG_SUBMIT = "submit";
    private static final String TAG_CANCEL = "cancel";
    
    // 时间转轮 自定义控件
    private LinearLayout layoutTimePickerView;
    
    public TimePickerView(PickerOptions pickerOptions) {
        super(pickerOptions.context);
        mPickerOptions = pickerOptions;
        initView(pickerOptions.context);
    }
    
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void initView(Context context) {
        setDialogOutSideCancelable();
        initViews();
        initAnim();
        
        if (mPickerOptions.customListener == null) {
            LayoutInflater.from(context).inflate(R.layout.pickerview_time, contentContainer);
            
            //顶部标题
            TextView tvTitle = (TextView) findViewById(R.id.sdk_tvTitle);
            View rv_top_bar = (View) findViewById(R.id.sdk_rv_topbar);
            
            //确定和取消按钮
            TextView btnSubmit = (TextView) findViewById(R.id.sdk_tv_finish);
            TextView btnCancel = (TextView) findViewById(R.id.sdk_tv_cancel);
            
            btnSubmit.setTag(TAG_SUBMIT);
            btnCancel.setTag(TAG_CANCEL);
            
            btnSubmit.setOnClickListener(this);
            btnCancel.setOnClickListener(this);
            
            //设置文字
            btnSubmit.setText(TextUtils.isEmpty(mPickerOptions.textContentConfirm) ? context.getResources().getString(R.string.pickerview_submit) :
                    mPickerOptions.textContentConfirm);
            btnCancel.setText(TextUtils.isEmpty(mPickerOptions.textContentCancel) ? context.getResources().getString(R.string.pickerview_cancel) :
                    mPickerOptions.textContentCancel);
            tvTitle.setText(TextUtils.isEmpty(mPickerOptions.textContentTitle) ? "" : mPickerOptions.textContentTitle);//默认为空
            
            //设置color
            btnSubmit.setTextColor(context.getResources().getColorStateList(mPickerOptions.textColorConfirm));
            btnCancel.setTextColor(context.getResources().getColorStateList(mPickerOptions.textColorCancel));
            tvTitle.setTextColor(context.getResources().getColor(mPickerOptions.textColorTitle));
            rv_top_bar.setBackground(context.getResources().getDrawable(mPickerOptions.bgColorTitle));
            
            //设置文字大小
            btnSubmit.setTextSize(mPickerOptions.textSizeSubmitCancel);
            btnCancel.setTextSize(mPickerOptions.textSizeSubmitCancel);
            tvTitle.setTextSize(mPickerOptions.textSizeTitle);
            
        } else {
            mPickerOptions.customListener.customLayout(LayoutInflater.from(context).inflate(mPickerOptions.layoutRes, contentContainer));
        }
        
        View select = findViewById(R.id.sdk_v_select_bg);
        if (select != null) {
            select.setBackgroundColor(context.getResources().getColor(mPickerOptions.selectItemBgColor));
        }
        
        // 时间转轮 自定义控件
        layoutTimePickerView = (LinearLayout) findViewById(R.id.sdk_timepicker);
        
        initWheelTime(context, layoutTimePickerView);
    }
    
    private void initWheelTime(Context context, LinearLayout timePickerView) {
        mWheelTimeWithWeek = new WheelTimeWithWeek(timePickerView, mPickerOptions.type, mPickerOptions.textGravity, mPickerOptions.textSizeContent);
        if (mPickerOptions.timeSelectChangeListener != null) {
            mWheelTimeWithWeek.setSelectChangeCallback(new ISelectTimeCallback() {
                @Override
                public void onTimeSelectChanged() {
                    try {
                        Date date = WheelTimeWithWeek.dateFormat.parse(mWheelTimeWithWeek.getTime());
                        mPickerOptions.timeSelectChangeListener.onTimeSelectChanged(date);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        
        mWheelTimeWithWeek.setDayIsShowWeek(mPickerOptions.dayIsShowWeek);
        mWheelTimeWithWeek.setLunarMode(mPickerOptions.isLunarCalendar);

//        if (mPickerOptions.startYear != 0 && mPickerOptions.endYear != 0
//                && mPickerOptions.startYear <= mPickerOptions.endYear) {
//            setRange();
//        }
        
        //若手动设置了时间范围限制
        if (mPickerOptions.getStartDate() != null && mPickerOptions.getEndDate() != null) {
            if (mPickerOptions.getStartDate().getTimeInMillis() > mPickerOptions.getEndDate().getTimeInMillis()) {
                throw new IllegalArgumentException("startDate can't be later than endDate");
            } else {
                resetRangDate();
            }
        } else if (mPickerOptions.getStartDate() != null) {
            if (mPickerOptions.getStartDate().get(Calendar.YEAR) < 1900) {
                throw new IllegalArgumentException("The startDate can not as early as 1900");
            } else {
                resetRangDate();
            }
        } else if (mPickerOptions.getEndDate() != null) {
            if (mPickerOptions.getEndDate().get(Calendar.YEAR) > 2100) {
                throw new IllegalArgumentException("The endDate should not be later than 2100");
            } else {
                resetRangDate();
            }
        } else {//没有设置时间范围限制，则会使用默认范围。
            resetRangDate();
        }
        
        resetSelectTime();
        mWheelTimeWithWeek.setLabels(mPickerOptions.label_year, mPickerOptions.label_month, mPickerOptions.label_day
                , mPickerOptions.label_hours, mPickerOptions.label_minutes, mPickerOptions.label_seconds);
        mWheelTimeWithWeek.setTextXOffset(mPickerOptions.x_offset_year, mPickerOptions.x_offset_month, mPickerOptions.x_offset_day,
                mPickerOptions.x_offset_hours, mPickerOptions.x_offset_minutes, mPickerOptions.x_offset_seconds);
        mWheelTimeWithWeek.setItemsVisible(mPickerOptions.itemsVisibleCount);
        mWheelTimeWithWeek.setAlphaGradient(mPickerOptions.isAlphaGradient);
        setOutSideCancelable(mPickerOptions.cancelable);
        mWheelTimeWithWeek.setCyclic(mPickerOptions.cyclic);
//        mWheelTimeWithWeek.setDividerColor(mPickerOptions.dividerColor);
//        mWheelTimeWithWeek.setDividerType(mPickerOptions.dividerType);
        
        mWheelTimeWithWeek.setLineSpacingMultiplier(mPickerOptions.lineSpacingMultiplier);
        mWheelTimeWithWeek.setTextColorOut(context.getResources().getColor(mPickerOptions.textColorOut));
        mWheelTimeWithWeek.setTextColorCenter(context.getResources().getColor(mPickerOptions.textColorCenter));
        mWheelTimeWithWeek.isCenterLabel(mPickerOptions.isCenterLabel);
    }
    
    
    /**
     * 设置默认时间
     */
    public void setSelectDateTime(long timeMillis) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timeMillis);
        mPickerOptions.setCurrentSelectDate(calendar);
        resetSelectTime();
    }
    
    /**
     * 更新时间选择范围
     * @param startTimeMillis
     * @param endTimeMillis
     */
    public void setRangDate(long startTimeMillis,long endTimeMillis){
        Calendar startDate = Calendar.getInstance();
        startDate.setTimeInMillis(startTimeMillis);
        Calendar endDate = Calendar.getInstance();
        endDate.setTimeInMillis(endTimeMillis);
        mPickerOptions.setStartDate(startDate);
        mPickerOptions.setEndDate(endDate);
        resetRangDate();
    }
    
    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private void resetRangDate() {
        mWheelTimeWithWeek.setRangDate(mPickerOptions.getStartDate(), mPickerOptions.getEndDate());
        initDefaultSelectedDate();
    }
    
    private void initDefaultSelectedDate() {
        //如果手动设置了时间范围
        if (mPickerOptions.getStartDate() != null && mPickerOptions.getEndDate() != null) {
            //若默认时间未设置，或者设置的默认时间越界了，则设置默认选中时间为开始时间。
            if (mPickerOptions.getCurrentSelectDate() == null || mPickerOptions.getCurrentSelectDate().getTimeInMillis() < mPickerOptions.getStartDate().getTimeInMillis()
                    || mPickerOptions.getCurrentSelectDate().getTimeInMillis() > mPickerOptions.getEndDate().getTimeInMillis()) {
                mPickerOptions.setCurrentSelectDate(mPickerOptions.getStartDate());
            }
        } else if (mPickerOptions.getStartDate() != null) {
            //没有设置默认选中时间,那就拿开始时间当默认时间
            mPickerOptions.setStartDate(mPickerOptions.getStartDate());
        } else if (mPickerOptions.getEndDate() != null) {
            mPickerOptions.setCurrentSelectDate(mPickerOptions.getEndDate());
        }
    }
    
    /**
     * 设置选中时间,默认选中当前时间
     */
    private void resetSelectTime() {
        
        Calendar calendar = Calendar.getInstance();
        
        if (mPickerOptions.getCurrentSelectDate() == null) {
            calendar.setTimeInMillis(System.currentTimeMillis());
        } else {
            calendar = mPickerOptions.getCurrentSelectDate();
        }
        
        mWheelTimeWithWeek.setSelectDate(calendar);
    }
    
    
    @Override
    public void onClick(View v) {
        String tag = (String) v.getTag();
        if (tag.equals(TAG_SUBMIT)) {
            returnData();
        } else if (tag.equals(TAG_CANCEL)) {
            if (mPickerOptions.cancelListener != null) {
                mPickerOptions.cancelListener.onClick(v);
            }
        }
        dismiss();
    }
    
    public void returnData() {
        if (mPickerOptions.timeSelectListener != null) {
            try {
                Date date = WheelTimeWithWeek.dateFormat.parse(mWheelTimeWithWeek.getTime());
                mPickerOptions.timeSelectListener.onTimeSelect(date, clickView);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 动态设置标题
     *
     * @param text 标题文本内容
     */
    public void setTitleText(String text) {
        TextView tvTitle = (TextView) findViewById(R.id.sdk_tvTitle);
        if (tvTitle != null) {
            tvTitle.setText(text);
        }
    }
    
    /**
     * 目前暂时只支持设置1900 - 2100年
     *
     * @param lunar 农历的开关
     */
    public void setLunarCalendar(boolean lunar) {
        try {
            int year, month, day, hours, minute, seconds;
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(WheelTimeWithWeek.dateFormat.parse(mWheelTimeWithWeek.getTime()));
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            hours = calendar.get(Calendar.HOUR_OF_DAY);
            minute = calendar.get(Calendar.MINUTE);
            seconds = calendar.get(Calendar.SECOND);
            
            mWheelTimeWithWeek.setLunarMode(lunar);
            mWheelTimeWithWeek.setLabels(mPickerOptions.label_year, mPickerOptions.label_month, mPickerOptions.label_day,
                    mPickerOptions.label_hours, mPickerOptions.label_minutes, mPickerOptions.label_seconds);
            mWheelTimeWithWeek.setPicker(year, month, day, hours, minute, seconds);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    public boolean isLunarCalendar() {
        return mWheelTimeWithWeek.isLunarMode();
    }
    
    
    @Override
    public boolean isDialog() {
        return mPickerOptions.isDialog;
    }
}
